package com.manner.groupon.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @Author: Manner
 * @Description: 基于 Redis 自增的Id生成器
 * @DateTime: 2024/10/7 14:39
 */
@Component
public class RedisIdWorker {

    //开始时间戳
    private static final Long BEGIN_TIMESTAMP = 1640995200L;
    private static final int COUNT_BITS = 32;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 时间戳加上序列号加上Redis自增生成全局唯一ID
     *
     * @param keyPrefix
     * @return long
     * @author manner
     * @date 2023/7/6 19:57
     */
    public long nextId(String keyPrefix) {
        //1.生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timeStamp = nowSecond - BEGIN_TIMESTAMP;
        //2.生成序列号,获取当前时间,精确到天数,每天一个新key,方便统计,还不会达到自增上限
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        //默认自增为1的序列号
        Long count = stringRedisTemplate.opsForValue().increment("incr:" + keyPrefix + date);
        //3.最后拼接成ID
        return timeStamp << COUNT_BITS | count;
    }
}
